<?php
// app/Controller/UsersController.php
class AdministrationController extends AppController
{

    var $uses = array(
        'User'
    );

    # Set the layout to use
    var $layout = 'admin_layout';

    public function beforeFilter($param_array = null)
    {
        parent::beforeFilter();
        $user_type = $this->Auth->user('user_type');
        $user_level = $this->Auth->user('user_level');
        if ($user_type != 'admin') {
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }

        /*if(in_array('Allow All',$param_array['user_levels'])){

        }
        else{
            if(in_array($user_level,$param_array['user_levels'])){

            }
            else{
                $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
            }
        }*/
    }

    public function index()
    {
        $this->redirect('users');
    }


    function users($type = 'get'){

        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $auth_user = $this->Session->read('loginData');
            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    //get users id for this company only

                    $condition_array = array(
                        'User.deleted' => 'n'
                    );

                    if (!empty($search_query)) {
                        if ($qtype == 'username') {
                            $condition_array = array(
                                'User.username' => $search_query,
                                'User.deleted' => 'n'
                            );
                        }
                        else {
                             $condition_array = array(
                                 "User.$qtype LIKE" => $search_query . '%',
                                 'User.deleted' => 'n'
                             );
                        }
                    }

                    $data_table = $this->User->find('all', array('conditions' => $condition_array, 'order' => "User.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => -1));
                    $data_table_count = $this->User->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['User']['id'],
                                'cell' => array(
                                    $obj['User']['id'],
                                    $obj['User']['fname'],
                                    $obj['User']['mname'],
                                    $obj['User']['lname'],
                                    $obj['User']['username'],
                                    $obj['User']['user_type'],
                                    $obj['User']['user_level'],
                                    $obj['User']['active']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    if ($_POST['id'] == 0) {
                        //check if username does not exist for in this company
                        $username = $_POST['username'];
                        $res = $this->_validateUsername($username);
                        if ($res) {
                            return json_encode(array('success' => 1, 'msg' => 'Username already exist.'));
                        }
                    }
                    $data = array('User' => $_POST);
                    $pass = '';
                    if ($_POST['id'] == 0) {
                        $pass = $this->randomPassString(6);
                        $data['User']['password'] = AuthComponent::password($pass);
                    }

                    if ($_POST['id'] > 0) {
                        $data['User']['modified_by'] = $auth_user['id'];
                    } else {
                        $data['User']['created_by'] = $auth_user['id'];
                    }

                    if ($this->User->save($this->sanitize($data['User']))) {
                        if($_POST['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        }
                        else{ //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!  The default password is '.$pass, 'id'=>$this->User->id));
                        }
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'reset_password':
                    $data = array(
                        'id'=>$_POST['id'],
                        'password'=>AuthComponent::password(trim($_POST['password']))
                    );
                    if ($this->User->save($this->sanitize($data))) {
                        return json_encode(array('code' => 0, 'msg' => 'Password has been reset.'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Password could not be reset.'));
                    }

                    break;

                case 'delete':
                    $ids = $_POST['ids'];
                    $modObj = ClassRegistry::init('User');
                    $result = $modObj->updateAll(
                        array('User.deleted' => "'y'"),
                        array('User.id' => $ids)
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                    break;
            }
        }

        $user_levels = array(
            array('id'=>'Normal','name'=>'Normal'),
            array('id'=>'Manager','name'=>'Manager'),
            array('id'=>'Administrator','name'=>'Administrator')
        );

        $user_type = array(
            array('id'=>'admin','name'=>'admin'),
            array('id'=>'accountant','name'=>'accountant'),
            array('id'=>'store','name'=>'store'),
            array('id'=>'warehouse','name'=>'warehouse'),
            array('id'=>'service_adviser','name'=>'service_adviser'),
            array('id'=>'workshop','name'=>'workshop')
        );

        $active = array(
            array('id'=>'Active','name'=>'Active'),
            array('id'=>'Disabled','name'=>'Disabled')
        );

        $page_title = 'Manage Users';
        $page_summary = 'Manage your users information';
        $page_icon = 'iconfa-group';

        $this->set(compact('page_title','page_summary','page_icon','user_levels','user_type','active'));
    }


    function _validateUsername($username = null)
    {
        $data = $this->User->getUserByLoginName($username);
        if ($data) {
            return true;
        } else {
            return false;
        }
    }


    function randomPassString($length)
    {
        return $this->randomString($length);
    }

}